package com.baor;


import com.baor.dao.CustomerDao;
import com.baor.dao.Equipment_holderDao;
import com.baor.dao.MonthlyDataDao;
import com.baor.domain.CustomerVO;
import com.baor.domain.MonthlyDataVo;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@SpringBootApplication
@MapperScan(basePackages = "com.baor.dao")
@EnableScheduling
@EnableTransactionManagement

public class Application implements WebMvcConfigurer {

    @Value("${file.path}")
    private String path;

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/images/**")
                .addResourceLocations("file:"+path);
    }

    @Autowired
    private CustomerDao customerDao;
    @Autowired
    private MonthlyDataDao monthlyDataDao;
    // 每月1号凌晨1点执行
    @Scheduled(cron = "0 0 1 1 * ?")
    public void generateMonthlyData() {
        // 获取所有设备持有者
        List<CustomerVO> holders = customerDao.selectList(null);

        // 获取当前时间和上一个月信息
        Calendar calendar = Calendar.getInstance();
        Date currentDate = new Date();
        calendar.add(Calendar.MONTH, -1);
        Date lastMonth = calendar.getTime();

        SimpleDateFormat monthFormat = new SimpleDateFormat("yyyy-MM");
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        String lastMonthStr = monthFormat.format(lastMonth);
        String currentTimeStr = dateFormat.format(currentDate);

        // 为每个持有者生成一条数据
        for (CustomerVO holder : holders) {
            MonthlyDataVo monthlyDataVo = new MonthlyDataVo();
            monthlyDataVo.setHolderId(Long.valueOf(holder.getId()));
            monthlyDataVo.setRealname(holder.getRealname());
            monthlyDataVo.setDevicesNumber(holder.getDevicesNumber());
            monthlyDataVo.setLastMonthInfo(lastMonthStr);
            monthlyDataVo.setBalance(holder.getBalance());
            monthlyDataVo.setCreateTime(currentTimeStr);

            // 保存生成的数据，这里假设使用专门的表存储月度数据
            monthlyDataDao.insert(monthlyDataVo);
        }
    }
}

